<?php

namespace apiend\modules\shop\models;

use Yii;
use common\helpers\Url;

/**
 * 统一搜索模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ShopUnifiedSearch extends \apiend\models\searchs\ProductSearch {

    use \common\traits\UnifiedKeyword;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['keyword'], 'required'],
            [['keyword'], 'validateKeyword'],
            [['store_id'], 'safe'],
        ];
    }

    /**
     * 构建查询query
     */
    public function buildQuery() {
//        $this->validate();
        $libs = $this->getLibs();
        $keywords = $this->getWords();
        $query = static::findActive('t', static::STATUS_ACTIVE);
        $query->with(['store', 'stats']);
        if (!empty($libs)) {
            $libQuery = clone $query;
            $query->union($libQuery->innerJoinWith('keywords key')->andWhere(['key.lib_id' => $libs]));
        }
        if (!empty($keywords)) {
            $likewhere = ['or'];
            foreach ($keywords as $word) {
                $likewhere[] = ['like', 't.name', $word];
            }
            $query->andFilterWhere($likewhere);
        }
        if ($this->store_id) {
            $query->andFilterWhere(['t.store_id' => $this->store_id]);
        }
        return $query;
    }

}
